import os
import re

import numpy as np
import pandas as pd

from utils.util import shoelace_area

lastMappID = 0
mountainPoints = []

def getMountainPoints(mapID, otherMap='无'):
    global mountainPoints
    global lastMappID
    if mountainPoints and lastMappID == mapID : return mountainPoints
    lastMappID = mapID
    if mapID == 1:
        excel_file = '..\\data\\4-拙政园数据坐标.xlsx'
    elif mapID == 2:
        excel_file = '..\\data\\4-留园数据坐标.xlsx'
    elif mapID == 3:
        excel_file = '..\\data\\4-寄畅园数据坐标.xlsx'
    elif mapID == 4:
        excel_file = '..\\data\\4-瞻园数据坐标.xlsx'
    elif mapID == 5:
        excel_file = '..\\data\\4-豫园数据坐标.xlsx'
    elif mapID == 6:
        excel_file = '..\\data\\4-秋霞圃数据坐标.xlsx'
    elif mapID == 7:
        excel_file = '..\\data\\4-沈园数据坐标.xlsx'
    elif mapID == 8:
        excel_file = '..\\data\\4-怡园数据坐标.xlsx'
    elif mapID == 9:
        excel_file = '..\\data\\4-耦园数据坐标.xlsx'
    elif mapID == 10:
        excel_file = '..\\data\\4-绮园数据坐标.xlsx'
    else:
        excel_file = os.path.join('..\\data\\', otherMap)
    # 读取Excel的“道路”工作表
    df = pd.read_excel(excel_file, sheet_name='假山')

    # 提取第一列数据（区分线段的坐标）
    raw_data = df.iloc[:, 0].dropna().astype(str)
    segments = []  # 存储所有线段
    current_segment = []  # 当前线段点列表

    for item in raw_data:
        if item.startswith('            {0;'):
            # 新线段开始：保存当前线段（如果有），并重置
            if current_segment:
                segments.append(current_segment)
            current_segment = []
            segment_id = int(re.findall(r'\d+', item)[0])  # 提取线段ID
        else:

            # 解析坐标点：格式为 "b.{x,y,z}"
            if mapID > 10:
                match = re.match(r'\(([-\d.]+), ([-\d.]+), ([-\d.]+)\)', item)
                if match:
                    x = float(match.group(1))
                    y = float(match.group(2))
                    current_segment.append((x, y))
            else:
                match = re.match(r'(\d+)\. \{([-\d.]+), ([-\d.]+), ([-\d.]+)\}', item)
                if match:
                    b = int(match.group(1))
                    x = float(match.group(2))
                    y = float(match.group(3))
                    current_segment.append((x, y))
    if current_segment:
        segments.append(current_segment)
    mountainPoints = segments
    return segments


def getMountainAreaAndCount(mapID):
    allMountainPoints = getMountainPoints(mapID)
    area = 0
    for mountainLine in allMountainPoints:
        if len(mountainLine) < 10: continue
        area = area + shoelace_area(mountainLine)
    return area, len(allMountainPoints)


def getMountainPerimeter(mapID):
    total_length = 0
    for line in getMountainPoints(mapID):
        # 将点集转换为NumPy数组（如果输入不是数组的话）
        points_arr = np.array(line)
        # 计算相邻点之间的差值 (x_{i+1} - x_i, y_{i+1} - y_i)
        diffs = np.diff(points_arr, axis=0)
        # 计算每个差值的欧几里得距离（二范数）
        distances = np.linalg.norm(diffs, axis=1)
        # 对所有距离求和
        total_length = total_length + np.sum(distances)
    return total_length